<template>
  <div class="create-order">
    <h2 class="page-title">Create Order</h2>

    <el-card>
      <!-- Steps -->
      <el-steps :active="active" finish-status="success" align-center style="margin-bottom: 40px;">
        <el-step title="Select Recipient" />
        <el-step title="Select Vials" />
        <el-step title="Select Clinic" />
        <el-step title="Confirm Order" />
      </el-steps>

      <!-- Step 1: Select Recipient -->
      <div v-if="active === 0" class="step-content">
        <h3>Select Recipient</h3>
        <el-form :model="searchForm" :inline="true" style="margin-bottom: 20px;">
          <el-form-item label="Keyword">
            <el-input
              v-model="searchForm.keyword"
              placeholder="Search recipient name/email"
              clearable
              style="width: 260px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadRecipients">
              <el-icon><Search /></el-icon>
              Search
            </el-button>
          </el-form-item>
        </el-form>

        <el-table
          :data="recipientList"
          highlight-current-row
          @current-change="handleRecipientSelect"
          style="width: 100%"
        >
          <el-table-column type="index" width="50" />
          <el-table-column prop="recipient_id" label="ID" width="80" />
          <el-table-column prop="full_name" label="Full Name" width="120" />
          <el-table-column prop="contact_email" label="Email" min-width="180" />
          <el-table-column prop="contact_phone" label="Phone" width="130" />
        </el-table>
      </div>

      <!-- Step 2: Select Vials -->
      <div v-if="active === 1" class="step-content">
        <h3>Select Vials</h3>
        <el-alert
          v-if="orderData.recipient"
          :title="`Selected Recipient: ${orderData.recipient.full_name}`"
          type="success"
          :closable="false"
          style="margin-bottom: 20px;"
        />

        <el-form :model="vialSearchForm" :inline="true" style="margin-bottom: 20px;">
          <el-form-item label="Blood Type">
            <el-select v-model="vialSearchForm.blood_type" placeholder="Select blood type" clearable style="width: 150px">
              <el-option label="Type A" value="A" />
              <el-option label="Type B" value="B" />
              <el-option label="Type AB" value="AB" />
              <el-option label="Type O" value="O" />
            </el-select>
          </el-form-item>
          <el-form-item label="Status">
            <el-select v-model="vialSearchForm.status" placeholder="Select status" clearable style="width: 150px">
              <el-option label="Available" value="Available" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadVials">
              <el-icon><Search /></el-icon>
              Search
            </el-button>
          </el-form-item>
        </el-form>

        <el-table
          :data="vialList"
          @selection-change="handleVialSelect"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="vial_id" label="Vial ID" width="100" />
          <el-table-column prop="donor_code" label="Donor Code" width="120" />
          <el-table-column prop="donor_name" label="Donor Name" width="120" />
          <el-table-column prop="blood_type" label="Blood Type" width="80" />
          <el-table-column prop="motility_percent" label="Motility (%)" width="110" />
          <el-table-column prop="sperm_count_mil" label="Sperm Count" width="110" />
          <el-table-column prop="collection_date" label="Collection Date" width="120">
            <template #default="{ row }">
              {{ formatDate(row.collection_date) }}
            </template>
          </el-table-column>
        </el-table>

        <div v-if="orderData.vials.length > 0" style="margin-top: 20px;">
          <el-tag v-for="vial in orderData.vials" :key="vial.vial_id" style="margin-right: 10px;">
            Vial #{{ vial.vial_id }}
          </el-tag>
        </div>
      </div>

      <!-- Step 3: Select Clinic -->
      <div v-if="active === 2" class="step-content">
        <h3>Select Clinic (Optional)</h3>
        <el-table
          :data="clinicList"
          highlight-current-row
          @current-change="handleClinicSelect"
          style="width: 100%"
        >
          <el-table-column type="index" width="50" />
          <el-table-column prop="clinic_id" label="ID" width="80" />
          <el-table-column prop="clinic_name" label="Clinic Name" min-width="200" />
          <el-table-column prop="address" label="Address" min-width="250" />
          <el-table-column prop="contact_person" label="Contact Person" width="120" />
          <el-table-column prop="contact_phone" label="Phone" width="130" />
        </el-table>
        <div style="margin-top: 20px;">
          <el-button type="text" @click="handleClinicSelect(null)">
            Skip this step without selecting a clinic
          </el-button>
        </div>
      </div>

      <!-- Step 4: Confirm Order -->
      <div v-if="active === 3" class="step-content">
        <h3>Confirm Order Information</h3>
        <el-descriptions :column="2" border style="margin-bottom: 20px;">
          <el-descriptions-item label="Recipient">
            {{ orderData.recipient?.full_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="Contact Phone">
            {{ orderData.recipient?.contact_phone || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="Clinic">
            {{ orderData.clinic?.clinic_name || 'None' }}
          </el-descriptions-item>
          <el-descriptions-item label="Vial Quantity">
            {{ orderData.vials.length }} vial(s)
          </el-descriptions-item>
        </el-descriptions>

        <h4>Vial Details</h4>
        <el-table :data="orderData.vials" border style="width: 100%; margin-top: 10px;">
          <el-table-column prop="vial_id" label="Vial ID" width="100" />
          <el-table-column prop="donor_code" label="Donor Code" width="150" />
          <el-table-column prop="donor_name" label="Donor Name" width="150" />
          <el-table-column prop="collection_date" label="Collection Date" width="120">
            <template #default="{ row }">
              {{ formatDate(row.collection_date) }}
            </template>
          </el-table-column>
        </el-table>

        <el-form :model="orderForm" label-width="120px" style="margin-top: 30px; max-width: 500px;">
          <el-form-item label="Total Price">
            <el-input-number
              v-model="orderForm.total_price"
              :min="0"
              :precision="2"
              style="width: 200px;"
            />
            USD
          </el-form-item>
        </el-form>
      </div>

      <!-- Button Group -->
      <div class="button-group">
        <el-button v-if="active > 0" @click="handlePrev">Previous</el-button>
        <el-button v-if="active < 3" type="primary" @click="handleNext" :disabled="!canNext">
          Next
        </el-button>
        <el-button v-if="active === 3" type="success" @click="handleSubmit" :loading="submitting">
          Submit Order
        </el-button>
        <el-button @click="handleCancel">Cancel</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { recipientAPI, vialAPI, clinicAPI, orderAPI } from '@/api'

const router = useRouter()

// Current step
const active = ref(0)

// Recipient search
const searchForm = reactive({
  keyword: ''
})

const recipientList = ref([])

// Vial search
const vialSearchForm = reactive({
  blood_type: '',
  status: 'Available'
})

const vialList = ref([])

// Clinic list
const clinicList = ref([])

// Order data
const orderData = reactive({
  recipient: null,
  vials: [],
  clinic: null
})

// Order form
const orderForm = reactive({
  total_price: 800.00
})

const submitting = ref(false)

// Check if can proceed to next step
const canNext = computed(() => {
  if (active.value === 0) {
    return orderData.recipient !== null
  }
  if (active.value === 1) {
    return orderData.vials.length > 0
  }
  if (active.value === 2) {
    return true // Clinic is optional
  }
  return false
})

// Load recipient list
const loadRecipients = async () => {
  try {
    const data = await recipientAPI.getList({ ...searchForm, pageSize: 1000 })
    recipientList.value = data.data || []
  } catch (error) {
    ElMessage.error('Failed to load recipient list')
  }
}

// Select recipient
const handleRecipientSelect = (row) => {
  orderData.recipient = row
}

// Load vial list
const loadVials = async () => {
  try {
    const data = await vialAPI.getList({ ...vialSearchForm, pageSize: 1000 })
    vialList.value = data.data || []
  } catch (error) {
    ElMessage.error('Failed to load vial list')
  }
}

// Select vials
const handleVialSelect = (selection) => {
  orderData.vials = selection
}

// Load clinic list
const loadClinics = async () => {
  try {
    const data = await clinicAPI.getList({ pageSize: 1000 })
    clinicList.value = data.data || []
  } catch (error) {
    ElMessage.error('Failed to load clinic list')
  }
}

// Select clinic
const handleClinicSelect = (row) => {
  orderData.clinic = row
}

// Previous step
const handlePrev = () => {
  if (active.value > 0) {
    active.value--
  }
}

// Next step
const handleNext = () => {
  if (!canNext.value) {
    if (active.value === 0) {
      ElMessage.warning('Please select a recipient')
    } else if (active.value === 1) {
      ElMessage.warning('Please select at least one vial')
    }
    return
  }
  
  if (active.value < 3) {
    active.value++
    
    // Load clinic list when entering step 3
    if (active.value === 2 && clinicList.value.length === 0) {
      loadClinics()
    }
    
    // Calculate total price when entering step 4
    if (active.value === 3) {
      orderForm.total_price = orderData.vials.length * 800
    }
  }
}

// Submit order
const handleSubmit = async () => {
  if (!orderData.recipient) {
    ElMessage.error('Please select a recipient')
    return
  }
  if (orderData.vials.length === 0) {
    ElMessage.error('Please select at least one vial')
    return
  }

  submitting.value = true
  try {
    const orderPayload = {
      recipient_id: orderData.recipient.recipient_id,
      clinic_id: orderData.clinic?.clinic_id || null,
      vial_ids: orderData.vials.map(v => v.vial_id),
      total_price: orderForm.total_price,
      status: 'Pending'
    }
    
    await orderAPI.create(orderPayload)
    ElMessage.success('Order created successfully!')
    router.push('/orders')
  } catch (error) {
    ElMessage.error('Failed to create order: ' + (error.message || 'Unknown error'))
  } finally {
    submitting.value = false
  }
}

// Cancel
const handleCancel = () => {
  router.back()
}

// Format date
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('en-US')
}

onMounted(() => {
  loadRecipients()
  loadVials()
})
</script>

<style scoped>
.create-order {
  padding: 0;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #303133;
}

.step-content {
  padding: 20px 0;
  min-height: 400px;
}

.step-content h3 {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #303133;
}

.step-content h4 {
  font-size: 16px;
  font-weight: 500;
  margin: 20px 0 10px 0;
  color: #606266;
}

.button-group {
  margin-top: 40px;
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.button-group .el-button {
  margin: 0 10px;
}

/* Custom table row highlight styles */
:deep(.el-table__body tr:hover > td.el-table__cell) {
  background-color: #ecf5ff !important; /* Hover - light blue */
}

:deep(.el-table__body tr.current-row > td.el-table__cell) {
  background-color: #c6e2ff !important; /* Selected row - deep blue */
}
</style>
